package com.im.file.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.im.file.UploadFile;
import com.im.file.bean.FileData;
import com.im.file.component.UploadComponent;
import com.im.file.dao.FileDataDAO;
import com.only.common.util.OnlyDateUtil;
import com.only.common.util.OnlyPropertiesUtil;

/**
 * 描述：
 * 
 * @author XiaHui
 * @date 2015年12月30日 下午8:59:57
 * @version 0.0.1
 */
@Service
@Transactional
public class FileService {
	
	private String upload = "upload/";
	@Autowired
	FileDataDAO fileDataDAO;
	@Autowired
	UploadComponent uploadComponent;

	public List<String> upload(HttpServletRequest request, String userId) {

		String basePath = request.getSession().getServletContext().getRealPath("/");

		String path = OnlyPropertiesUtil.getPropertyByClassPtah("/setting/config.properties", "file.save.path");

		StringBuilder rootPath = new StringBuilder((StringUtils.isBlank(path)) ? basePath : path);// 拼接文件上传目录
		rootPath.append(upload + "file/");

		StringBuilder nodePath = new StringBuilder("");
		nodePath.append(OnlyDateUtil.getCurrentYear());
		nodePath.append("/");
		nodePath.append(OnlyDateUtil.getCurrentMonth());
		nodePath.append("/");
		nodePath.append(OnlyDateUtil.getCurrentDay());
		nodePath.append("/");
		UploadFile uploadFile = new UploadFile();
		List<FileData> fileDataList = uploadFile.uploadByIo(request, rootPath.toString(), nodePath.toString(), userId);
		return add(fileDataList);
	}

	private List<String> add(List<FileData> fileDataList) {
		List<String> list = new ArrayList<String>();
		if (null != fileDataList && !fileDataList.isEmpty()) {
			fileDataDAO.saveOrUpdateList(fileDataList);

			for (FileData fd : fileDataList) {
				list.add(fd.getId());
			}
		}
		return list;
	}

	public FileData getFileData(String id) {
		return this.fileDataDAO.get(FileData.class, id);
	}
}
